//
//  YYGWebview.m
//  YiYuanGou
//
//  Created by zhangtongle on 2017/5/5.
//  Copyright © 2017年 同乐1234521. All rights reserved.
//

#import "YYGWebview.h"
#import "WeakScriptMessageDelegate.h"
#import "LGEncrypt.h"
#import "YYGShareView.h"
#import "LGManager.h"

static NSString* const WXPaySuccess    = @"YYL.wxPaySuccess";
static NSString* const WXChargeSuccess = @"YYL.wxChargeSuccess";
static NSString* const WXLoginSuccess  = @"YYL.wxLoginSuccess";
static NSString* const WXShareSuccess  = @"YYL.wxShareSuccess";
static NSString* const WXAppSystemInfo = @"YYL.appGetSystemInfo";


@interface YYGWebview () <WKScriptMessageHandler, UIWebViewDelegate> {
    NSArray *_jsMethodHandleArr;
}
@property (nonatomic, strong) UIView *webView;

@property (nonatomic, strong) JSContext *jsContent;

@property (strong, nonatomic) NSDictionary *shareDic;

@property (assign, nonatomic) CGFloat sysVer;

@property (strong, nonatomic) UIProgressView *progressView;
@property (assign, nonatomic) BOOL isShowProgress;
@end

@implementation YYGWebview

+ (YYGWebview *)yygWebView:(CGRect)frame {
    YYGWebview *webContainer = [[NSBundle mainBundle] loadNibNamed:@"YYGWebview" owner:nil options:nil].firstObject;
    [webContainer setFrame:frame];
    
    frame.origin.y = 21;
    frame.size.height -= 20;
    
    webContainer.sysVer = [UIDevice currentDevice].systemVersion.floatValue;
    if (webContainer.sysVer >= 8.0) {
        WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:frame];
        webContainer.webView = wkWebView;
        
        [webContainer p_addScriptMessageHandlers];

//        [webContainer enableNavigationProgress];
        
    } else {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
        webContainer.webView = webView;
        
        webView.delegate = webContainer;
        webView.scrollView.bounces = NO;
        webView.scrollView.showsVerticalScrollIndicator = NO;
        webView.delegate = webContainer;
        
        [webContainer p_setDelegate];
    }
    

    [webContainer addSubview:webContainer.webView];

    return webContainer;
}

- (UIProgressView *)progressView
{
    if (!_progressView)
    {
        UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 20, self.frame.size.width, 1)];
        progressView.tintColor = [UIColor blueColor];
        progressView.trackTintColor = [UIColor grayColor];
        [self addSubview:progressView];
        self.progressView = progressView;
    }
    return _progressView;
}
#pragma mark 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == (WKWebView *)self.webView && [keyPath isEqualToString:@"estimatedProgress"])
    {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1)
        {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }
        else
        {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

- (void)loadRequest:(NSString *)urlStr {
    if (self.sysVer >= 8.0) {
        [(WKWebView *)self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];

    } else {
        [(UIWebView *)self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
        
    }

}
- (void)navHidden:(BOOL)hidden {
    CGRect webFrame = self.webView.frame;

    if (hidden) {
        self.navHeight.constant = 0;
        [self layoutIfNeeded];

        webFrame.origin.y = 20;
        webFrame.size.height = self.frame.size.height - 20;
        self.webView.frame = webFrame;

    } else {
        self.navHeight.constant = 64;
        [self layoutIfNeeded];

        webFrame.origin.y = 64;
        webFrame.size.height = self.frame.size.height - 64;
        self.webView.frame = webFrame;
    }
    
    if (self.isShowProgress) {
        [self layoutProgress:hidden];

    }
}

- (void)layoutProgress:(BOOL)isNavHidden {
    CGRect newFrame = self.progressView.frame;
    
    if (isNavHidden) {
        newFrame.origin.y = 20;
        
    } else {
        newFrame.origin.y = 63;
    }
    
    self.progressView.frame = newFrame;
}

- (void)setMainWebView {
    _isMainWebView = YES;
}

- (void)enableNavigationProgress {
    self.isShowProgress = YES;
    
    [(WKWebView *)self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

}

- (void)dealloc {
    
    if (self.sysVer >= 8.0) {
        [self p_removeScriptMessageHandlers];
        
        if (self.isShowProgress) {
            [(WKWebView *)self.webView removeObserver:self forKeyPath:@"estimatedProgress"];

        }
    } else {
        
    }
}


#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSString *methodName = message.name;
    NSString *mathodPara = message.body;

    if ([self respondsToSelector:NSSelectorFromString(methodName)]) {
        [self performSelector:NSSelectorFromString(methodName) withObject:mathodPara afterDelay:0];

    } else if ([self respondsToSelector:NSSelectorFromString([NSString stringWithFormat:@"%@:", methodName])]) {
        [self performSelector:NSSelectorFromString([NSString stringWithFormat:@"%@:", methodName]) withObject:mathodPara afterDelay:0];

    } else {
        NSLog(@"WebView call 未注册方法:%@", methodName);

    }
    
    
#ifdef DEBUG
    //    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, self.frame.size.width, 100)];
    //    label.backgroundColor = [UIColor grayColor];
    //    [label setText:[NSString stringWithFormat:@"方法名:%@, 参数:%@", methodName, paraStr]];
    //    [label setTextColor:[UIColor redColor]];
    //    [[UIApplication sharedApplication].keyWindow addSubview:label];
    //
    //
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        [label removeFromSuperview];
    //    });
#endif
}


#pragma mark - JSObjectDelegate

- (void)openUrl:(NSString *)jsonStr {
    NSDictionary *urlDic = [LGEncrypt dictionaryWithJsonString:jsonStr];

    NSLog(@"openUrl: urlInfo=%@", urlDic);
    
    if ([urlDic[@"target"] isEqualToString:@"_blank"]) {
        YYGWebview *webContainer = [YYGWebview yygWebView:self.superview.bounds];
        [webContainer loadRequest:urlDic[@"url"]];
        [self.superview addSubview:webContainer];

    } else {
        [self loadRequest:urlDic[@"url"]];
        
    }
    
}

- (void)setPageInfo:(NSString *)jsonStr {
    [self navHidden:NO];
    
    NSDictionary *pageDic = [LGEncrypt dictionaryWithJsonString:jsonStr];
    
    self.navTitleL.text = pageDic[@"title"];
    
    int backBtnShowStatu = [pageDic[@"backButton"] intValue];
    if (backBtnShowStatu == 1) {
        self.navBackBtn.hidden = NO;
    } else {
        self.navBackBtn.hidden = YES;
    }
}

- (void)setShareInfo:(NSString *)jsonStr {
    self.navShareBtn.hidden = NO;
    
    self.shareDic = [LGEncrypt dictionaryWithJsonString:jsonStr];
}

- (void)wxPay:(NSString *)jsonStr {
    [self p_payInWeiXin:jsonStr isCharge:NO];
}

- (void)wxCharge:(NSString *)jsonStr {
    [self p_payInWeiXin:jsonStr isCharge:YES];
}

- (void)wxLogin {
    __weak typeof(self)weakSelf = self;
    [[LGLoginManager sharedInstance] loginInWeiXin:^(NSError *error, NSDictionary *result) {
        NSString *state = @"0";
        NSString *code = @"";
        if (!error) {
            state = @"1";
            code = result[@"code"];
        }
        
        [weakSelf p_ocCallJS:WXLoginSuccess parameter:@{@"c":state, @"code":code}];
    }];
    
}

- (void)deviceInfo {
    [self p_ocCallJS:WXAppSystemInfo parameter:@{@"c":@"1", @"deviceName":@"ios", @"sysVer":[NSString stringWithFormat:@"%f", self.sysVer]}];
}

- (void)callQQ:(NSString *)jsonStr {
    NSDictionary *infoDic = [LGEncrypt dictionaryWithJsonString:jsonStr];

    NSLog(@"WebView Call callQQ, qq:%@", infoDic[@"id"]);
    
    //qqNumber就是你要打开的QQ号码， 也就是你的客服号码。
    NSString  *qqNumber = infoDic[@"id"];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
        NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",qqNumber]];
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        webView.delegate = self;
        [webView loadRequest:request];
        [self.superview addSubview:webView];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您没有安装QQ" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
        [alertView show];
        
    }
}


#pragma mark - Event
- (IBAction)navBack:(id)sender {
    if (self.isMainWebView) {
        if (self.sysVer >= 8.0) {
            [(WKWebView *)self.webView goBack];
            
        } else {
            [(UIWebView *)self.webView goBack];
            
        }
    } else {
        [self removeFromSuperview];

    }
}
- (IBAction)navShare:(id)sender {
    YYGShareView *shareView = [YYGShareView sharedInstance];
    [shareView setFrame:self.bounds];
    [shareView shareViewHidden:NO];
    
    [YYGShareView sharedInstance].shareCallback = ^(int shareKind) {
        if (!self.shareDic) {
            [self p_ocCallJS:WXShareSuccess parameter:@{@"c":@"0"}];
            return;
        }
        
        
        LGShareContent *shareContent = [[LGShareContent alloc] init];
        
        if (shareKind == 0) {
            // 微信好友分享
            shareContent.wxScene = 0;
            
        } else {
            // 微信朋友圈分享
            shareContent.wxScene = 1;
            
        }
        
        // 分享链接
        shareContent.contentType = LGShareContentTypeLink;
        shareContent.contentTitle = self.shareDic[@"title"];
        shareContent.contentDescription = self.shareDic[@"desc"];
        shareContent.thumbImageURL = self.shareDic[@"image"];
        shareContent.contentURL = self.shareDic[@"url"];
        
        __weak typeof(self)weakSelf = self;
        [[LGShareManager shareInstance] share:shareContent shareType:LGShareTypeWeiXin callback:^(NSError *error, NSDictionary *result) {
            NSString *state = @"0";
            if (!error) {
                state = @"1";
            }
            
            [weakSelf p_ocCallJS:WXShareSuccess parameter:@{@"c":state}];
            
        }];
        
    };
}

#pragma mark - other
- (void)p_ocCallJS:(NSString *)methodName parameter:(NSDictionary *)dic {
    NSString *jsString = [NSString stringWithFormat:@"%@('%@')", methodName, [LGEncrypt getJsonString:dic]];
    NSLog(@"p_ocCallJS jsString:%@", jsString);
    if (self.sysVer >= 8.0) {
        [(WKWebView *)self.webView evaluateJavaScript:jsString completionHandler:^(id _Nullable object, NSError * _Nullable error) {
            
        }];
        
        
    } else {
        [(UIWebView *)self.webView stringByEvaluatingJavaScriptFromString:[LGEncrypt getJsonString:dic]];
    }
}

- (void)p_payInWeiXin:(NSString *)orderInfo isCharge:(BOOL)isCharge {
    __weak typeof(self)weakSelf = self;
    [[LGPayManager sharedInstance] payInWeiXin:[LGEncrypt dictionaryWithJsonString:orderInfo] callback:^(NSError *error, NSDictionary *result) {
        NSString *state = @"0";
        if (!error) {
            state = @"1";
        }
        
        NSString *methodName = WXPaySuccess;
        if (isCharge) {
            methodName = WXChargeSuccess;
            
        }
        [weakSelf p_ocCallJS:methodName parameter:@{@"c":state}];
        
    }];
    
}


- (void)p_addScriptMessageHandlers {
    _jsMethodHandleArr = @[@"openUrl", @"setPageInfo", @"setShareInfo", @"wxPay", @"wxCharge", @"wxLogin", @"deviceInfo", @"callQQ"];
    
    WeakScriptMessageDelegate *weakDelegate = [[WeakScriptMessageDelegate alloc] initWithDelegate:self];
    WKWebView *webView = (WKWebView *)self.webView;
    
    for (NSString *name in _jsMethodHandleArr) {
        [webView.configuration.userContentController addScriptMessageHandler:weakDelegate name:name];
        
    }
    
}
- (void)p_removeScriptMessageHandlers {
    WKWebView *webView = (WKWebView *)self.webView;
    
    for (NSString *name in _jsMethodHandleArr) {
        [webView.configuration.userContentController removeScriptMessageHandlerForName:name];
        
    }
}


- (void)p_setDelegate {
    
    self.jsContent = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.jsContent[@"YYGInterface"] = self;
    self.jsContent.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        context.exception = exception;
        NSLog(@"异常信息：%@", exception);
    };
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    if (!webView.isLoading) {
        [self p_setDelegate];
        
    }
}
@end


